package com.TexasHoldem.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;



public class NetUtil {
	/**
	 * 地址转换为字符串
	 * 
	 * @param inetAddress
	 * @return
	 */
	private static String address2String(InetAddress inetAddress) {
		byte[] address = inetAddress.getAddress();
		StringBuffer res = new StringBuffer();
		for (int i = 0; i < address.length; i++) {
			if (i > 0)
				res.append(".");
			res.append(String.valueOf(address[i] & 0xff));
		}
		return res.toString();
	}

	/**
	 * 获得本地IP
	 * 
	 * @return
	 * @throws SocketException
	 */
	public static String getLocalHostIP() {
		String prefix = "10.";
		try {

			Enumeration<NetworkInterface> networkInterfacesEnum = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfacesEnum.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfacesEnum
						.nextElement();
				Enumeration<InetAddress> inetAddressEnum = networkInterface
						.getInetAddresses();
				while (inetAddressEnum.hasMoreElements()) {
					InetAddress inetAddress = inetAddressEnum.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						String addrStr = address2String(inetAddress);
						if (prefix.length() != 0) {
							if (addrStr.startsWith(prefix))
								return addrStr;
							// if (addrStr.indexOf(prefix)==0) {
							// return addrStr;
							// }
						} else
							return addrStr;
					}
				}
			}
			return "127.0.0.1";
		} catch (SocketException e) {
			throw new RuntimeException("getLocalHost ip address error", e);
		}
	}

	public static boolean isSameSubnet(String ip1, String ip2) {
		if (!isVaildInetAddress(ip1) || !isVaildInetAddress(ip2))
			return false;

		String s1 = ip1.substring(0, ip1.lastIndexOf("."));
		String s2 = ip2.substring(0, ip2.lastIndexOf("."));

		return s1.equals(s2);
	}

	/**
	 * 判断是否合法的网络IP地址
	 * 
	 * @param ipStr
	 * @return
	 */
	public static boolean isVaildInetAddress(String ipStr) {
		if (ipStr == null || ipStr.trim().length() == 0)
			return false;

		String[] na = ipStr.split("\\x2e");
		if (na.length != 4)
			return false;

		for (int i = 0; i < 4; i++) {
			int addr = 0;
			try {
				addr = Integer.parseInt(na[i]);
			} catch (Exception e) {
				return false;
			}

			if (addr < 0 || addr > 254)
				return false;

			if (i == 0 && addr == 0)
				return false;

			if (i == 3 && addr == 0)
				return false;

		}

		return true;
	}

	/**
	 * 毫秒转化为时间
	 * 
	 * @param time
	 * @return
	 */
	public static String getTime(long time) {
		
		return null;

	}

	public static void main(String[] args) {
		System.out.println("_____" + getTime(1000 * 60 * 60 * 5));
	}
}
